<template>
  <div>
    <BasicModal
      @register="registerModal"
      v-bind="$attrs"
      @ok="handleSubmit"
      :closeFunc="handleClose"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>

<script setup lang="ts">
  import { defineEmits, ref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form';
  import { addKeyValueSchema, editAttributeSchema } from './modal.data';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  const emit = defineEmits(['success', 'register']);
  const modeValue = ref<string>('');
  const optionsValue = ref<string>('');
  const keyName = ref<string>('');
  const [registerForm, { validate, resetSchema, setFieldsValue, updateSchema, resetFields }] =
    useForm({
      layout: 'vertical',
      showActionButtonGroup: false,
      ...modalFormStyleSetting,
    });
  const [registerModal, { setModalProps, closeModal }] = useModalInner(
    async ({ mode, optionValue, record }) => {
      modeValue.value = mode;
      optionsValue.value = optionValue;
      let schemas: FormSchema[] = [];
      if (modeValue.value === 'add') {
        setModalProps({
          loading: true,
          title: '添加属性',
          confirmLoading: true,
          ...modalStyleSetting,
        });
        schemas = addKeyValueSchema;
        resetSchema(schemas);
      } else if (modeValue.value == 'edit') {
        setModalProps({ loading: true, title: '编辑属性', confirmLoading: true });
        keyName.value = record.key;
        schemas = editAttributeSchema;
        resetSchema(schemas);
        handleEditAttribute(record);
      }
      setModalProps({ loading: false, confirmLoading: false });
    },
  );
  // 编辑弹窗加载
  const handleEditAttribute = ({ type, value }) => {
    setFieldsValue({
      valueType: type,
    });
    switch (type) {
      case 'string':
        setFieldsValue({
          stringValue: value,
        });
        break;
      case 'integer':
        setFieldsValue({
          integerValue: value,
        });
        break;
      case 'decimal':
        setFieldsValue({
          decimalValue: value,
        });
        break;
      case 'boolean':
        setFieldsValue({
          booleanValue: value == 'false' ? false : true,
        });
        updateSchema({
          field: 'booleanValue',
          label: JSON.parse(value) ? '真' : '假',
          componentProps: ({ formActionType }) => {
            return {
              onChange: (e: any) => {
                const { updateSchema } = formActionType;
                updateSchema({
                  field: 'booleanValue',
                  label: e.target.checked ? '真' : '假',
                });
              },
            };
          },
        });
        break;
      case 'json':
        setFieldsValue({
          jsonValue: value,
        });
        break;
    }
  };

  // 提交
  const handleSubmit = async () => {
    setModalProps({ confirmLoading: true });
    if (modeValue.value == 'add') {
      try {
        const values = await validate();
        closeModal();
        emit('success', {
          key: 'add',
          values: { ...values },
        });
        resetFields();
      } catch (e) {}
    } else if (modeValue.value == 'edit') {
      try {
        const values = await validate();
        closeModal();
        emit('success', {
          values: { ...values, keyName: keyName.value },
        });
        resetFields();
      } catch (e) {}
    }
    setModalProps({ confirmLoading: false });
  };
  // 关闭弹窗
  const handleClose = async () => {
    resetFields();
    return true;
  };
</script>
